package cn.edu.sgu.www.mhxysy.redis;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.util.CollectionUtils;
import cn.edu.sgu.www.mhxysy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 基于StringRedisTemplate封装的redis工具类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Component
public class StringRedisUtils implements RedisUtils {

    private final StringRedisTemplate stringRedisTemplate;
    private final ValueOperations<String, String> valueOperations;

    @Autowired
    public StringRedisUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.valueOperations = stringRedisTemplate.opsForValue();
    }

    @Override
    public String get(String key) {
        return valueOperations.get(key);
    }

    @Override
    public List<String> multiGet(Set<String> keys) {
        return valueOperations.multiGet(keys);
    }

    @Override
    public Set<String> keys(String pattern) {
        return stringRedisTemplate.keys(pattern);
    }

    @Override
    public void set(String key, String value) {
        valueOperations.set(key, value);
    }

    @Override
    public void set(String key, String value, long timeout, TimeUnit timeUnit) {
        valueOperations.set(key, value, timeout, timeUnit);
    }

    @Override
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public void deleteByPattern(String pattern) {
        Set<String> keys = stringRedisTemplate.keys(pattern);

        if (CollectionUtils.isNotEmpty(keys)) {
            stringRedisTemplate.delete(keys);
        }
    }

    @Override
    public Long incrBy(String key) {
        return valueOperations.increment(key);
    }

    @Override
    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public void expire(String key, long timeout, TimeUnit timeUnit) {
        stringRedisTemplate.expire(key, timeout, timeUnit);
    }

    @Override
    public String uuid() {
        String key = RedisKeyPrefixes.PREFIX_CURRENT_TIMESTAMP;

        String value = get(key);

        if (value == null) {
            value = StringUtils.uuid();

            set(key, value, 30, TimeUnit.MINUTES);
        }

        return incrBy(key).toString(); // 通过自增来保证获取的key唯一
    }

}